package bitfield

// A Bitfield represents the pieces that a peer has
// 用位来标识 发送/下载状态
// 8 位 = 1 字节
type Bitfield []byte

// HasPiece tells if a bitfield has a particular index set
// 校验当前 index piece 是否已经下载
func (bf Bitfield) HasPiece(index int) bool {
	// 确定当前 index 属于那个byte
	byteIndex := index / 8
	// 在 byte 中具体的 位置
	offset := index % 8
	if byteIndex < 0 || byteIndex >= len(bf) {
		return false
	}

	// 255 >>
	return bf[byteIndex]>>uint(7-offset)&1 != 0
}

// SetPiece sets a bit in the bitfield
// 设置当前 index piece 下载状态
func (bf Bitfield) SetPiece(index int) {
	byteIndex := index / 8
	offset := index % 8

	// silently discard invalid bounded index
	if byteIndex < 0 || byteIndex >= len(bf) {
		return
	}
	bf[byteIndex] |= 1 << uint(7-offset)
}
